from db import database
from myserial import lserial
from utils import utils
import sys
import threading


index = 0
finish = 0

def send_data():
    global index
    if sendorder == "r":
        index = utils.util.getRamdom(0, datalist.__len__() - 1)

    my_serial_port.send(utils.util.str_translate(datalist[index]))
    if finish == 0:
        t = threading.Timer(interval * 0.001, send_data)
        t.start()


if sys.argv.__len__() != 6:
    print("input para error")
print("port = ", sys.argv[1], "dbfile = ", sys.argv[2],"database =", sys.argv[3], "interval = ", sys.argv[4],
      "sendorder = ", sys.argv[5])
my_serial_port = lserial.SerialPort(sys.argv[1], 115200, 8, 1, 'N')
my_serial_port.start()
conn, curse = database.DataBase.db_open(sys.argv[2])
databasename = sys.argv[3]
datalist = database.DataBase.db_command(conn, curse, "SELECT * from " + databasename)
print("datalist = ")
for i in datalist:
    print(i)

interval = int(sys.argv[4])
sendorder = sys.argv[5]

t = threading.Timer(interval * 0.001, send_data)
t.start()
if sendorder != "r":
    while index < datalist.__len__() :
        tstr = input(datalist[index][15] +" index = "+ str(index) +"\n")
        if tstr == "Y" or tstr == "y":
            if index == (datalist.__len__()) - 1:
                print("send all msg")
                finish = 1
                break
        elif tstr == "N" or tstr == "n":
            print("\033[1;35m", datalist[index][15], " error! \033[0m")
            if index == (datalist.__len__()) - 1:
                print("send all msg")
                finish = 1
                break
        elif tstr == "exit":
            print("exit")
            finish = 1
            exit(0)
        else:
            index = (-1 if(index == 0) else index-1 )
        index += 1
        tstr = ""









